package test.mongo;

import java.net.UnknownHostException;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

public class test {
	public static void main(String[] args){
		try {
			Mongo mongo = new Mongo();	// "localhost", 27017, "newdb"			
			
			
			//查询所有的Database  
	        for (String name : mongo.getDatabaseNames()) {  
	            System.out.println("dbName: " + name);  
	        }  
	        
	        DB db = mongo.getDB("newdb"); 
	        //查询所有的聚集集合  
	        for (String name : db.getCollectionNames()) {  
	            System.out.println("collectionName: " + name);  
	        }  
			
	        
	        DBCollection users = db.getCollection("user");
	        //查询所有的数据  
	        DBCursor cur = users.find();  
	        while (cur.hasNext()) {  
	            System.out.println(cur.next());  
	        }  
	        System.out.println(cur.count());  
	        System.out.println(cur.getCursorId());  
	        System.out.println(JSON.serialize(cur));  
	        System.out.println("=====另一个测试======");
	        DBCollection coll = db.getCollection("test");
	        for(int i = 0; i < 100; i++){   
	        	coll.insert(new BasicDBObject().append("i", i));   
	        } 
	        System.out.println(coll.getCount());   
	        cur = coll.find();   
	        while(cur.hasNext()){   
	        	System.out.println(cur.next());   
	        }   
	        BasicDBObject query = new BasicDBObject();   
	        query.put("i", 71);   
	        cur = coll.find(query);   
	        while(cur.hasNext()){   
	        	System.out.println(cur.next());   
	        }  
	        
	        System.out.println("我们也可以做20 < i <= 30的查询");
	        query = new BasicDBObject();   
	        query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));   
	        cur = coll.find(query);   
	        while(cur.hasNext()){   
	        	System.out.println(cur.next());   
	        } 
	        
	       System.out.println("创建索引");
	       coll.createIndex(new BasicDBObject("i", 1)); 	       
	       List<DBObject> list = coll.getIndexInfo();
	       for(DBObject o : list){   
	    	   System.out.println(o);   
	       }  
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}		
		
	}

}
